<template>
  <div class="file-message-container">
    <!-- 图片文件 -->
    <div v-if="isImage" class="image-preview" @click="handlePreviewImage">
      <el-image
        :src="fileUrl"
        fit="cover"
        :preview-src-list="[fileUrl]"
        hide-on-click-modal
        class="preview-image"
      >
        <template #error>
          <div class="image-error">
            <el-icon><Picture /></el-icon>
            <span>图片加载失败</span>
          </div>
        </template>
      </el-image>
      <!-- <div class="file-info">
        <div class="file-name">{{ fileName }}</div>
      </div> -->
    </div>

    <!-- 视频文件 -->
    <div v-else-if="isVideo" class="video-preview">
      <video
        :src="fileUrl"
        controls
        class="preview-video"
        controlsList="nodownload nofullscreen"
        disablePictureInPicture
        @click.stop
      ></video>
      <div class="file-info">
        <!-- <div class="file-name">{{ fileName }}</div> -->
        <div class="file-actions">
          <el-button type="primary" link size="small" @click="openVideo">
            <el-icon class="icon"><FullScreen /></el-icon>
            全屏播放
          </el-button>
          <el-button type="primary" link size="small" @click="downloadFile">
            <el-icon class="icon"><Download /></el-icon>
            下载
          </el-button>
        </div>
      </div>
    </div>

    <!-- 其他文件 -->
    <div v-else class="other-file">
      <div class="file-icon">
        <el-icon v-if="isPDF"><Document /></el-icon>
        <el-icon v-else-if="isAudio"><Headset /></el-icon>
        <el-icon v-else-if="isArchive"><Fold /></el-icon>
        <el-icon v-else-if="isText"><Files /></el-icon>
        <el-icon v-else><Document /></el-icon>
      </div>
      <div class="file-info">
        <div class="file-name">{{ fileName }}</div>
        <div class="file-type">{{ fileTypeText }}</div>
      </div>
      <div class="file-actions">
        <el-button type="primary" link size="small" @click="downloadFile">
          <el-icon class="icon"><Download /></el-icon>
          下载
        </el-button>
      </div>
    </div>
  </div>

  <!-- 视频预览弹窗 -->
  <el-dialog
    v-model="videoDialogVisible"
    title="视频预览"
    width="80%"
    destroy-on-close
    center
    fullscreen
    class="video-dialog"
  >
    <div class="video-dialog-container">
      <video
        :src="fileUrl"
        controls
        autoplay
        controlsList="nodownload nofullscreen"
        disablePictureInPicture
        class="fullscreen-video"
      ></video>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from "vue";
import { ElMessage, ElDialog } from "element-plus";
import {
  Picture,
  Document,
  Headset,
  Fold,
  Files,
  FullScreen,
  Download,
} from "@element-plus/icons-vue";

const props = defineProps({
  /**
   * 文件URL
   */
  fileUrl: {
    type: String,
    required: true,
  },
  /**
   * 文件名（可选）
   */
  fileName: {
    type: String,
    default: "",
  },
  /**
   * 文件大小（可选）
   */
  fileSize: {
    type: Number,
    default: 0,
  },
});

// 视频预览弹窗控制
const videoDialogVisible = ref(false);

// 根据URL后缀判断文件类型
const fileExtension = computed(() => {
  if (!props.fileUrl) return "";
  const url = props.fileUrl.toLowerCase();
  const match = url.match(/\.([a-z0-9]+)(?:\?|#|$)/i);
  return match ? match[1].toLowerCase() : "";
});

// 文件类型标识
const isImage = computed(() => {
  const imageExt = ["jpg", "jpeg", "png", "gif", "bmp", "webp", "svg"];
  return imageExt.includes(fileExtension.value);
});

const isVideo = computed(() => {
  const videoExt = ["mp4", "webm", "ogg", "mov", "avi", "wmv", "flv", "mkv"];
  return videoExt.includes(fileExtension.value);
});

const isPDF = computed(() => fileExtension.value === "pdf");
const isAudio = computed(() => {
  const audioExt = ["mp3", "wav", "ogg", "aac", "flac"];
  return audioExt.includes(fileExtension.value);
});
const isArchive = computed(() => {
  const archiveExt = ["zip", "rar", "7z", "tar", "gz"];
  return archiveExt.includes(fileExtension.value);
});
const isText = computed(() => {
  const textExt = [
    "txt",
    "doc",
    "docx",
    "xls",
    "xlsx",
    "ppt",
    "pptx",
    "csv",
    "json",
    "xml",
    "html",
    "css",
    "js",
  ];
  return textExt.includes(fileExtension.value);
});

// 显示的文件类型文本和大小
const fileTypeText = computed(() => {
  let typeText = "";
  if (isPDF.value) typeText = "PDF文档";
  else if (isAudio.value) typeText = "音频文件";
  else if (isArchive.value) typeText = "压缩文件";
  else if (isText.value) typeText = "文档文件";
  else typeText = fileExtension.value ? `.${fileExtension.value}文件` : "未知类型文件";

  // 如果有文件大小，添加到类型文本中
  if (props.fileSize) {
    typeText += ` (${formatFileSize(props.fileSize)})`;
  }

  return typeText;
});

// 根据URL和可能存在的fileName获取文件名
const fileName = computed(() => {
  if (props.fileName) return props.fileName;

  // 尝试从URL中解析文件名
  try {
    if (props.fileUrl) {
      const url = new URL(props.fileUrl);
      const pathParts = url.pathname.split("/");
      const lastPart = pathParts[pathParts.length - 1];

      // 如果URL中有文件名部分，返回解码后的文件名
      if (lastPart && lastPart.includes(".")) {
        return decodeURIComponent(lastPart);
      }
    }
  } catch (e) {
    console.error("解析URL文件名失败:", e);
  }

  // 如果没有文件名，根据类型返回默认名称
  if (isImage.value) return `图片.${fileExtension.value}`;
  if (isVideo.value) return `视频.${fileExtension.value}`;
  if (isPDF.value) return `文档.pdf`;
  if (isAudio.value) return `音频.${fileExtension.value}`;

  return `文件.${fileExtension.value || "unknown"}`;
});

// 打开视频预览弹窗
function openVideo() {
  videoDialogVisible.value = true;
}

// 处理图片预览
function handlePreviewImage() {
  // ElImage组件自带预览功能，点击即可预览
  // 这里预留接口，可以添加其他逻辑
}

// 下载文件
function downloadFile() {
  if (!props.fileUrl) {
    ElMessage.warning("文件链接无效");
    return;
  }

  try {
    const a = document.createElement("a");
    a.href = props.fileUrl;
    a.download = fileName.value;
    a.target = "_blank";
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  } catch (error) {
    console.error("下载文件失败:", error);
    ElMessage.error("下载文件失败");
  }
}

// 格式化文件大小
function formatFileSize(size) {
  if (!size) return "";

  const KB = 1024;
  const MB = KB * 1024;
  const GB = MB * 1024;

  if (size < KB) {
    return size + " B";
  } else if (size < MB) {
    return (size / KB).toFixed(2) + " KB";
  } else if (size < GB) {
    return (size / MB).toFixed(2) + " MB";
  } else {
    return (size / GB).toFixed(2) + " GB";
  }
}
</script>

<style scoped>
.file-message-container {
  width: 100%;
  border-radius: 4px;
  overflow: hidden;
}

.image-preview {
  cursor: pointer;
  position: relative;
  border-radius: 6px;
  overflow: hidden;
  width: 100%;
}

.preview-image {
  width: 100%;
  max-width: 300px;
  max-height: 200px;
  object-fit: cover;
  border-radius: 6px;
  display: block;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 150px;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 14px;
}

.image-error .el-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.video-preview {
  border-radius: 6px;
  overflow: hidden;
  background-color: #f5f7fa;
}

.preview-video {
  width: 100%;
  border-radius: 6px 6px 0 0;
  display: block;
}

.other-file {
  display: flex;
  align-items: center;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

.file-icon {
  font-size: 36px;
  margin-right: 12px;
  color: #409eff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.file-icon .el-icon {
  font-size: 24px;
}

.file-info {
  flex: 1;
  min-width: 0;
  padding: 8px 12px;
}

.file-name {
  font-weight: 500;
  margin-bottom: 4px;
  word-break: break-all;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.file-type {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.file-actions {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  flex-wrap: wrap;
  margin-top: 4px;
}

.file-actions .el-button {
  margin-right: 8px;
  margin-bottom: 4px;
}

.icon {
  margin-right: 4px;
}

/* 视频弹窗相关样式 */
.video-dialog-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.8);
}

.fullscreen-video {
  max-width: 90%;
  max-height: 80vh;
}

:deep(.video-dialog) {
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.video-dialog .el-dialog__body) {
  padding: 0;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.video-dialog .el-dialog__header) {
  padding: 10px 20px;
  margin: 0;
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
}

:deep(.video-dialog .el-dialog__title) {
  color: white;
}

:deep(.video-dialog .el-dialog__headerbtn .el-dialog__close) {
  color: white;
}
</style>
